<?php

class Country_ManageController extends Core_Controller_Action_Standard
{
    public function init()
    {
        $headStyle = new Zend_View_Helper_HeadLink();
        if (Zend_Registry::isRegistered('StaticBaseUrl')) {
          $headStyle->prependStylesheet(Zend_Registry::get('StaticBaseUrl')
                  . 'application/modules/Core/externals/styles/admin/main.css');
        } 
        
        $viewer = Engine_Api::_()->user()->getViewer();
        if (!$viewer || empty( $viewer->user_id ) ) {
            return $this->_forward('notfound');
        }
        
        $country_Id = $this->_getParam('country_id',$this->_getParam('cid',$this->_getParam('c_id',0)));
        $managerT = Engine_Api::_()->getDbtable('managers','country');
        $isAdmin = $managerT->isAdmin($country_Id, $viewer->user_id);
        if (!$isAdmin) {
            return $this->_forward('notfound');
        }
    }
    
    public function pollListAction(){
        
        $country_id = $this->_getParam('country_id',$this->_getParam('cid',0));
        $this->view->country_id = $country_id;
                           
        $table = Engine_Api::_()->getDbtable('polls','country');
        $select = $table->select()
                        ->where('poll_type = 1');
                        
                                                
        $this->view->paginator = $paginator = Zend_Paginator::factory($select);
        $page = $this->_getParam('page',1);
        $paginator->setItemCountPerPage(20);
        $this->view->paginator = $paginator->setCurrentPageNumber($page);
    }
    
    public function pollValueAction(){
        $request = $this->getRequest();
        $country_id = $request->getParam('cid',0);
        $poll_id = $request->getParam('pid',0);
        $poll = Engine_Api::_()->getItem('country_poll',$poll_id);
        $country = Engine_Api::_()->getItem('country_country', $country_id);
        if(!$country) return;
                
        $this->view->form = $form = new Country_Form_Manage_Poll(array('poll'=>$poll,'country'=>$country_id));
        if (!$this->getRequest()->isPost()) return;
        if (!$form->isValid($this->getRequest()->getPost()) ) return false;
        
        $values = $this->_getParam('poll_options');
        
        
        $voteT  = Engine_Api::_()->getDbtable('pollvotes','country');
        $voteT->delete(array(
            'country_id = ?' => $country_id,
            'poll_id = ?'    => $poll_id
        ));
        foreach($values as $key => $value){
            $row = $voteT->createRow();
            $row->country_id = $country_id;
            $row->poll_id = $poll_id;
            $row->polloption_id =  $key;
            $row->value = $value;
            $row->save();
        }
        return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array($this->view->translate('This value had been change successed.'))
       	));
        
    }
    public function editCountryAction(){
        
        $request = $this->getRequest();
        $country_id = $request->getParam('cid',0);
      	$country = Engine_Api::_()->getItem('country_country', $country_id);
        if(!$country) return;
        
        $this->view->form = $form = new Country_Form_Create();
        
        $populate_array = array();
        
        
        $populate_array['country_title'] = $country->title;
        $populate_array['description_country'] = $country->description;
		$populate_array['national_anthem_title'] = $country->national_anthem_title;
		$populate_array['president_name'] = $country->president_name;
        $form->populate($populate_array);
        
        $viewer = Engine_Api::_()->user()->getViewer();
      	
        $form->setTitle('Edit this country');
        
         if($request->isPost()){
			$form->getElement('new_flag')->setOptions(array('required' => false));
			$form->getElement('new_big_map')->setOptions(array('required' => false));
			$form->getElement('new_small_map')->setOptions(array('required' => false));
            if(!$form->isValid($request->getPost())) return;
            
            $values = $form->getValues();
            
            try{
                
                if( !empty($_FILES['new_flag']) && $_FILES['new_flag']['error'] == 0) { // set flag to country
                    $new_flag_id = $country->setPhoto($form->new_flag);
                    $country->flag_photo_id = $new_flag_id;
                }
                if( !empty($_FILES['new_big_map']) && $_FILES['new_big_map']['error'] == 0) { // set big map to country
                    $big_map_id = $country->setPhoto($form->new_big_map);
                    $country->big_map_photo_id = $big_map_id;
                }
                if( !empty($_FILES['new_small_map']) && $_FILES['new_small_map']['error'] == 0) { // set small map to country
                    $small_map_id = $country->setPhoto($form->new_small_map);
                    $country->small_map_photo_id = $small_map_id;
                }
				 if( !empty($_FILES['president_image_id']) && $_FILES['president_image_id']['error'] == 0) { // set small map to country
                    $president_image_id = $country->setPhoto($form->president_image_id);
                    $country->president_image_id = $president_image_id;
                }
				
				if( !empty($_FILES['national_anthem_id']) && $_FILES['national_anthem_id']['error'] == 0) { // set national anthem
                    $national_anthem_id = $country->createSong($form->national_anthem_id);
                    $country->national_anthem_id = $national_anthem_id;
                }
				
                $country->title = $values['country_title']; 
                $country->description = $values['description_country'];
				$country->national_anthem_title = $values['national_anthem_title'];
				$country->president_name = $values['president_name'];
                $country->owner_id = $viewer->getIdentity();
                
                $country->save();
                
                $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 10,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Adding Successfully.'))
            	));
            
            }
            catch(exception $e){
				throw($e);die;
                $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array($this->view->translate('Adding Error.'))
            	));
            }
            
        }
    }
    
    
    
    
    public function addManagerAction(){
        $country_id = $this->_getParam('cid',0);
        $user_id = $this->_getParam('uid',0);
        $this->view->form = $form = new Country_Form_Delete();
        $form->setTitle('Set memeber to manager');
        $form->setDescription('Could you want to set this member to manager of country?');
        $form->getElement('submit')->setLabel('Yes');
        if ($this->getRequest()->isPost()) {
            
            $managerT = Engine_Api::_()->getDbtable('managers','country');
            if (!$managerT->isManager($country_id,$user_id)) {
                $row = $managerT->createRow();
                $row->user_id = $user_id;
                $row->country_id = $country_id;
                $row->save();
            } 
            
            return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 1000,
                    'messages' => array($this->view->translate('This member had been set to manager successed.'))
           	));
            
        }
        
        
    }
    
    public function removeManagerAction(){
        $country_id = $this->_getParam('cid',0);
        $user_id = $this->_getParam('uid',0);
        $this->view->form = $form = new Country_Form_Delete();
        $form->setTitle('Remove manager of country');
        $form->setDescription('Could you want to remove this manager from country?');
        $form->getElement('submit')->setLabel('Yes');
        if ($this->getRequest()->isPost()) {
            
            $managerT = Engine_Api::_()->getDbtable('managers','country');
            $managerT->removeManager($country_id,$user_id);
            
            return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 1000,
                    'messages' => array($this->view->translate('This manager had been remove from country successed.'))
           	));
            
        }
        
        
    }
    
    
    
    
    public function indexAction(){
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('country_admin_main', array(), '');
                
        $country_id = $this->_getParam('cid', 0);
        
        if(!empty($country_id)){
            
            $country = Engine_Api::_()->getItem('country_country', $country_id);
            $this->view->country = $country;
        }
        
        $this->view->country_id = $country_id;
        
        $country_field_Tb = Engine_Api::_()->getDbTable('countryfields','country') ;
        
        $select = $country_field_Tb->select()
                                    ->where('country_id = ?', $country_id);
        
        $this->view->paginator = $paginator = Zend_Paginator::factory($select);
        $page = $this->_getParam('page',1);
        $paginator->setItemCountPerPage(10);
        $this->view->paginator = $paginator->setCurrentPageNumber($page);
        
    }
    
    public function photosAction(){
                
        $country_id = $this->_getParam('cid', 0);
        
        if(!empty($country_id)){
            
            $country = Engine_Api::_()->getItem('country_country', $country_id);
            $this->view->country = $country;
        }
        
        $this->view->country_id = $country_id;
        
        $introduceMedia = Engine_Api::_()->getDbTable('introducemedias','country') ;
        
        $select = $introduceMedia->select()
                                    ->where('country_id = ?', $country_id);
        
        $this->view->paginator = $paginator = Zend_Paginator::factory($select);
        $page = $this->_getParam('page',1);
        $paginator->setItemCountPerPage(20);
        $this->view->paginator = $paginator->setCurrentPageNumber($page);
        
    }
    
    public function deleteMediaAction(){
        $media_id = $this->_getParam('m_id',0);
        $this->view->form = $form = new Country_Form_Delete();
        $form->setTitle('Remove media of country');
        $form->setDescription('Could you want to remove this media from country?');
        $form->getElement('submit')->setLabel('Yes');
        if ($this->getRequest()->isPost()) {
            
            $mediaT = Engine_Api::_()->getDbtable('introducemedias','country');
            $media = Engine_Api::_()->getItem('introducemedia',$media_id);
            if (!$media) {
                return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array($this->view->translate('This media can not found.'))
           	));
            }
            
            $db = $mediaT->getAdapter();
            
            try{
                $db->beginTransaction();
                $media->delete();
                $db->commit();
                return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 1000,
                    'messages' => array($this->view->translate('This media had been delete from country successed.'))
           	    ));
                
            }
            catch(Exception $e){
                $db->rollBack();
                return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array($this->view->translate('This media can not delete, please contact admin.'))
           	));
            }
            
            
            
        }
        
        
    }
    
    public function addAction(){
        $request = $this->getRequest();
        $country_id = $this->_getParam('c_id', 0);
      	$this->view->form = $form = new Country_Form_Admin_Countryfield_Create();
        $form->setTitle('Create New Field');
        
        
        if($request->isPost()){
            
            if(!$form->isValid($request->getPost())) return;
            try{
                $values = $form->getValues();
            
                $country_field_Tb = Engine_Api::_()->getDbTable('countryfields','country') ;
                
                $new_item = $country_field_Tb->createRow();
                
                $new_item->field_id = $values['field_id'];
                $new_item->country_id = $country_id;
                $new_item->detail = $values['detail'];
                $new_item->creation_date = date("Y-m-d H:i:s");
                $new_item->modified_date = date("Y-m-d H:i:s");
                
                $new_item->save();
                
                $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 10,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Adding Successfully.'))
            	));
            }
            catch(Exception $e){
                ///
                $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Adding Error.'))
            	));
            }
            
            
        }
    }
    public function deleteAction()
    {
        
        $request = $this->getRequest();
        $country_field_id = $request->getParam('cf_id',0);
        $country_field = Engine_Api::_()->getItem('country_countryfield', $country_field_id);
        $this->view->form = $form = new Country_Form_Admin_Countryfield_Delete();
        if($request->isPost())
        {
            if(!$form->isValid($request->getPost())) return;
            $country_field->delete();
            $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Successful.'))
            	));
            
        }
    }
    public function editAction(){
        $request = $this->getRequest();
        $country_field_id = $request->getParam('cf_id',0);
        $country_field = Engine_Api::_()->getItem('country_countryfield', $country_field_id);
      	
        $values = array();
        $values['field_id'] = $country_field->field_id;
        $values['detail'] = $country_field->detail;
          
        $this->view->form = $form = new Country_Form_Admin_Countryfield_Create();
        $form->setTitle('Edit Field');
        $form->populate($values);
        
        
        if($request->isPost()){
            
            if(!$form->isValid($request->getPost())) return;
            try{
                $values = $form->getValues();
                
                $country_field->field_id = $values['field_id'];
                $country_field->detail = $values['detail'];
                $country_field->modified_date = date("Y-m-d H:i:s");
                
                $country_field->save();
                
                $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 10,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Adding Successfully.'))
            	));
            }
            catch(Exception $e){
                ///
                $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Adding Error.'))
            	));
            }
            
            
        }
    }
    
    
    
    
    public function uploadAction()
    {

        $cid = $this->_getParam('cid',0);
        if( isset($_GET['ul']) || isset($_FILES['Filedata']) ) return $this->_forward('upload-photo', null, null, array('format' => 'json'));
    
        //if( !$this->_helper->requireAuth()->setAuthParams('introducemedia', null, 'create')->isValid() ) return;
    
        // Render
        /*$this->_helper->content
            //->setNoRender()
            ->setEnabled()
            ;
    */
        // Get form
        $this->view->form = $form = new Country_Form_Album(array('countryId'=>$cid));
    
        if( !$this->getRequest()->isPost() )
        {
          if( null !== ($album_id = $this->_getParam('album_id')) )
          {
            $form->populate(array(
              'album' => $album_id
            ));
          }
          return;
        }
    
        if( !$form->isValid($this->getRequest()->getPost()) )
        {
          return;
         }
    
        $db = Engine_Api::_()->getItemTable('introducemedias')->getAdapter();
        $db->beginTransaction();
    
        try
        {
          $album = $form->saveValues();
    
          $db->commit();
        }
        catch( Exception $e )
        {
          $db->rollBack();
          throw $e;
        }
        
        $this->_helper->redirector->gotoRoute(array('action' => 'editphotos', 'album_id' => $album->album_id), 'album_specific', true);
   }

  public function uploadPhotoAction()
  {
   // if( !$this->_helper->requireAuth()->setAuthParams('introducemedia', null, 'create')->isValid() ) return;
    $cid = $this->_getParam('cid',0);
    $this->view->form = $form = new Country_Form_Photo(array('countryId'=>$cid));
    if( !$this->getRequest()->isPost() ) return;
    
    if( !$this->_helper->requireUser()->checkRequire() )
    {
      $this->view->status = false;
      $this->view->error = Zend_Registry::get('Zend_Translate')->_('Max file size limit exceeded (probably).');
      return;
    }

    if( !$this->getRequest()->isPost() )
    {
      $this->view->status = false;
      $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid request method');
      return;
    }

    $values = $this->getRequest()->getPost();
    if( empty($values['Filename']) && !isset($_FILES['Filedata']))
    {
      $this->view->status = false;
      $this->view->error = Zend_Registry::get('Zend_Translate')->_('No file');
      return;
    }

    if( !isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name']) )
    {
      $this->view->status = false;
      $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid Upload');
      return;
    }

    $db = Engine_Api::_()->getDbtable('introducemedias', 'country')->getAdapter();
    $db->beginTransaction();

    try
    {
      $viewer = Engine_Api::_()->user()->getViewer();
      $description = $values['description'];
      
      $photoTable = Engine_Api::_()->getDbtable('introducemedias', 'country');
      $photo = $photoTable->createRow();
      $photo->setFromArray(array(
        'owner_id' => $viewer->getIdentity()
      ));
      $photo->description = $description;
      $photo->save();
      
      $photo->setPhoto($_FILES['Filedata']);
      $photo->country_id = $cid;
      $photo->save();
      
      $this->view->status = true;
      $this->view->name = $_FILES['Filedata']['name'];
      $this->view->photo_id = $photo->getIdentity();

      $db->commit();
      
      return $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Your media had been add successfull.'))
            	));
                

    } catch(Exception  $e ) {
      $db->rollBack();
       return $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array($this->view->translate('Your media can not upload, please contact admin.'))
            	));
      }
      
    
  }
  
  public function removeMediaAction(){
     $media_id = $this->_getParam('media_id',0);
     $media = Engine_Api::_()->getItem('introducemedia',$media_id);
     $table = Engine_Api::_()->getDbtable('introducemedias','country');
     $db = $table->getAdapter();
     $db->beginTransaction();

     try
     {
      $media->delete();
      $db->commit();
     }

     catch( Exception $e )
     {
      $db->rollBack();
      throw $e;
     }
     
    
    
  }
    
    
 
    
}
